package com.itsu.shirojwt.shiro.realm;

import javax.annotation.Resource;

import com.itsu.shirojwt.entity.User;
import com.itsu.shirojwt.service.UserService;
import com.itsu.shirojwt.shiro.token.JWTToken;
import com.itsu.shirojwt.utils.JWTUtil;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class JWTRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JWTToken jwtToken = (JWTToken) token;
        String tokenStr = (String) jwtToken.getCredentials();
        User user = null;
        try {
            String userName = JWTUtil.getUserName(tokenStr);
            user = userService.getUserByUserName(userName);
        } catch (Exception e) {
            throw new AuthenticationException(e);
        }
        return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

	

}